﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace Sensor.UI.Converters;

/// <summary>
/// 布尔值到串口状态文本的转换器
/// </summary>
/// <remarks>
/// 将布尔值转换为对应的串口状态文本显示
/// true: "关闭串口"
/// false: "打开串口"
/// </remarks>
public class BoolToPortStatusText : IValueConverter
{
    #region IValueConverter 实现

    /// <summary>
    /// 将布尔值转换为串口状态文本
    /// </summary>
    /// <param name="value">要转换的布尔值</param>
    /// <param name="targetType">目标类型</param>
    /// <param name="parameter">转换参数</param>
    /// <param name="culture">区域信息</param>
    /// <returns>转换后的状态文本</returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ToValue(value);
    }

    /// <summary>
    /// 将串口状态文本转换回布尔值
    /// </summary>
    /// <param name="value">要转换的状态文本</param>
    /// <param name="targetType">目标类型</param>
    /// <param name="parameter">转换参数</param>
    /// <param name="culture">区域信息</param>
    /// <returns>转换后的布尔值</returns>
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ToValue(value);
    }

    #endregion

    #region 私有方法

    /// <summary>
    /// 将值转换为对应的串口状态文本
    /// </summary>
    /// <param name="value">要转换的值</param>
    /// <returns>转换后的状态文本</returns>
    /// <remarks>
    /// 如果值为 true，返回"关闭串口"
    /// 如果值为 false，返回"打开串口"
    /// 如果值无法解析，返回"未知状态"
    /// </remarks>
    private static string ToValue(object value)
    {
        if (value != null && bool.TryParse(value.ToString(), out bool result))
        {
            return result ? "关闭串口" : "打开串口";
        }
        return "未知状态";
    }

    #endregion
}